import Vue from 'vue'

import vuex from 'Vuex'

Vue.use(vuex);



let car = window.JSON.parse(localStorage.getItem('cart') || '[]')

const store = new vuex.Store({
  state: {
    //cart 为对象{id,count,selected,price}
    cart: car,//购物车数组
  },
  mutations: {
    addToCar(state, goods) {
      //将商品添加购物车
      //如果购物车中有这个商品就更新数量，若无，就直接push
      let flag = false;
      state.cart.some(item => {
        if (item.id == goods.id) {
          item.count += goods.count;
          flag = true;
          return true;
        }
      })
      if (!flag) {
        state.cart.push(goods);
      }

      //持久化存储购物车里的数据，存在localStorage
      localStorage.setItem('cart', window.JSON.stringify(state.cart));
    },
    updateGoodsCount(state, goods) {
      state.cart.some(item => {
        if (item.id == goods.id) {
          item.count = goods.count
          return true;
        }
      })
      localStorage.setItem('cart', window.JSON.stringify(state.cart));
    },
    delFromCart(state, id) {
      state.cart.some((item, i) => {
        if (item.id == id) {
          state.cart.splice(i, 1)
          return true
        }
      })
      localStorage.setItem('cart', window.JSON.stringify(state.cart));
    },
    changeSelectState(state,obj){
      state.cart.some(item=>{
         if(item.id==obj.id){
           item.selected=obj.selected;
           return true;
         }
      })
      localStorage.setItem('cart', window.JSON.stringify(state.cart));
    }
  },
  getters: {
    totalcount(state) {
      console.log(state)
      let c = 0
      state.cart.forEach(item => c += item.count)
      //  这是徽标上的值
      return c
    },
    idstr(state) {
      let arr = []
      state.cart.forEach(item => arr.push(item.id))
      return arr.join(',')
    },
    countObj(state) {
      let o = {}
      state.cart.forEach(item => o[item.id] = item.count)
      return o
    },
    selectedObj(state) {
      //id 对应得商品是否被选中
      let o = {}
      state.cart.forEach(item => o[item.id] = item.selected)
      return o
    },
    selectedcount(state){
     //勾选的数量
     let c=0;
     state.cart.forEach(item=>{
       if(item.selected){
         c+=item.count
       }
     })
     return c
   },
   pricecount(state){
    //勾选的数量
    let c=0;
    state.cart.forEach(item=>{
      if(item.selected){
        c+=item.count*item.price
      }
    })
    return c
  },

  }

})
export default store